import 'dart:io';

import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';

class StorageManagementPage extends StatefulWidget {
  StorageManagementPage({Key key}) : super(key: key);

  @override
  _StorageManagementPageState createState() => _StorageManagementPageState();
}

class _StorageManagementPageState extends State<StorageManagementPage> {
  @override
  void initState() {
    // TODO: implement initState
    loadCache();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TopAppBar(context, "存储管理"),
      body: Column(
        children: [
          InkWell(
            onTap: () {
              _clearCache();
            },
            child: Container(
              height: 60,
              color: Colors.white,
              child: ListTile(
                leading: Text(
                  "清除缓存:  $_cacheSizeStr",
                  style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                ),
                trailing: Icon(Icons.keyboard_arrow_right),
              ),
            ),
          ),
          Divider(
            height: 1,
            indent: ScreenUtil().setWidth(10),
            color: Color.fromRGBO(248, 248, 248, 1),
            thickness: ScreenUtil().setHeight(1),
          ),
          ///8.2 ios上架 暂不展示
          // InkWell(
          //   onTap: () {
          //     //
          //   },
          //   child: Container(
          //     color: Colors.white,
          //     height: 60,
          //     child: ListTile(
          //       leading: Text(
          //         "管理聊天记录",
          //         style: TextStyle(fontSize: ScreenUtil().setSp(15)),
          //       ),
          //       trailing: Icon(Icons.keyboard_arrow_right),
          //     ),
          //   ),
          // ),
        ],
      ),
    );
  }

  var _cacheSizeStr;

  ///加载缓存
  Future<Null> loadCache() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDir);
      /*tempDir.list(followLinks: false,recursive: true).listen((file){
          //打印每个缓存文件的路径
        print(file.path);
      });*/
      print('临时目录大小: ' + value.toString());
      setState(() {
        _cacheSizeStr = _renderSize(value);
      });
    } catch (err) {
      print(err);
    }
  }

  /// 递归方式 计算文件的大小
  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        if (children != null)
          for (final FileSystemEntity child in children)
            total += await _getTotalSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (e) {
      print(e);
      return 0;
    }
  }

  void _clearCache() async {
    //此处展示加载loading
    try {
      Directory tempDir = await getTemporaryDirectory();
      //删除缓存目录
      await delDir(tempDir);
      await loadCache();
      toast('清除缓存成功');
    } catch (e) {
      print(e);
      toast('清除缓存失败');
    } finally {
      //此处隐藏加载loading
    }
  }

  ///递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await delDir(child);
        }
      }
      await file.delete();
    } catch (e) {
      print(e);
    }
  }

  ///格式化文件大小
  _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = List()..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }
}
